class Solution
{
public:
    int maxSumAfterPartitioning(vector<int> &arr, int k)
    {
        int n = arr.size();
        vector<int> dp(n, 0);
        dp[0] = arr[0];
        for (int i = 1; i < n; ++i)
        {
            int subMax = arr[i];
            for (int j = i; j >= max(0, i - k + 1); --j)
            {
                subMax = max(subMax, arr[j]);
                if (j > 0)
                {
                    dp[i] = max(dp[i], dp[j - 1] + subMax * (i - j + 1));
                }
                else
                {
                    dp[i] = max(dp[i], subMax * (i - j + 1));
                }
            }
        }
        return dp[n - 1];
    }
};